layui.config({
    base: "/assets/js/lib/"
}).use(['layer', 'form', 'router', 'element','md5'], function () {
    var $ = layui.jquery, layer = layui.layer,
        router = layui.router,
        form = layui.form, element = layui.element;

    var urls = {
        upload: "/oss/rest/upload",
        setAvatar: "/my/setAvatar",
        modifyData: "/my/modifyData",
        resetPwd: "/my/resetPwd"
    };

    form.verify({
        confirmPwd: function (value, item) {
            var pwd = $("#newPwd").val();
            if (pwd != '') {
                if (value != pwd) {
                    return "两次密码要一致";
                }
            }
        }
    });

    if ($('.upload-img')[0]) {
        layui.use('upload', function (upload) {
            var avatarAdd = $('.avatar-add');
            upload.render({
                elem: '.upload-img',
                url: urls.upload,
                size: 50,
                before: function () {
                    avatarAdd.find('.loading').show();
                },
                done: function (res) {
                    if (res.code == '000000') {
                        $.post(urls.setAvatar, {
                            avatar: res.message
                        }, function () {
                            window.location.reload(true);
                        });
                    } else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    avatarAdd.find('.loading').hide();
                },
                error: function () {
                    avatarAdd.find('.loading').hide();
                }
            });
        });
    }
    form.on("submit(*)", function (data) {
        var othis = $(this), key = othis.attr('key');
        form[key].call(this, data);
        return false;
    });

    var form = {
        set_mine: function (data) {
            router.post({
                url: urls.modifyData,
                data: data.field,
                success: function () {
                    location.reload();
                }
            });
        },
        resetPwd: function (data) {
            data.field["oldPwd"] = $.md5(data.field["oldPwd"]);
            data.field["newPwd"] = $.md5(data.field["newPwd"]);
            router.post({
                url: urls.resetPwd,
                data: data.field,
                success: function () {
                    layer.msg("密码修改成功",{time:2000},function () {
                        location.reload();
                    });
                }
            });
        }
    };

    //显示当前tab
    if (location.hash) {
        element.tabChange('mine', location.hash.replace(/^#/, ''));
    }

    element.on('tab(mine)', function () {
        var othis = $(this), layid = othis.attr('lay-id');
        if (layid) {
            location.hash = layid;
        }
    });

});